package com.ai3d.rfid.base.app

import android.app.Application
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

/**
 * base class for obtain a ViewModel of global scope in Activity/Fragment
 * if u want to obtain Application-level ViewModel without extending BaseApp,
 * u can copy the code to your customized Application,then write the Expanding function to
 * get global ViewModel as GetViewModelExt#getAppViewModel
 */

open class BaseApp : Application(), ViewModelStoreOwner {

    private lateinit var mViewModelStore: ViewModelStore

    private var mFactory: ViewModelProvider.Factory? = null

    override fun getViewModelStore(): ViewModelStore {
        return mViewModelStore
    }

    override fun onCreate() {
        super.onCreate()
        mViewModelStore = ViewModelStore()
    }

    /**
     * obtain a ViewModel of global scope
     */
    fun getAppViewModelProvider(): ViewModelProvider {
        return ViewModelProvider(this, this.getAppFactory())
    }

    private fun getAppFactory(): ViewModelProvider.Factory {
        if (mFactory == null) {
            mFactory = ViewModelProvider.AndroidViewModelFactory.getInstance(this)
        }
        return mFactory as ViewModelProvider.Factory
    }
}